﻿using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;

namespace OverlakeApp.HomeTile
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        private static volatile bool _classInitialized;

        /// <remarks>
        /// ScheduledAgent constructor, initializes the UnhandledException handler
        /// </remarks>
        public ScheduledAgent()
        {
            if (!_classInitialized)
            {
                _classInitialized = true;
                // Subscribe to the managed exception handler
                Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    Application.Current.UnhandledException += ScheduledAgent_UnhandledException;
                });
            }
        }

        /// Code to execute on Unhandled Exceptions
        private void ScheduledAgent_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }


        public string Day { get; set; }
        public string DayNoSchool { get; set; }
        public string Lunch { get; set; }

        private Uri RandomImage
        {
            get
            {
                Random rnd = new Random();
                int img = rnd.Next(6);
                string uri = img.ToString() + ".jpg";

                return new Uri(uri, UriKind.Relative);
            }
        }

        public Uri FrontImage
        {
            get
            {
                return this.RandomImage;
            }
        }

        public Uri BackImage
        {
            get
            {
                return this.RandomImage;
            }
        }

        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            string day, lunch;
            using (ViewModels.OverlakeViewModel vm = new ViewModels.OverlakeViewModel(false))
            {
                day = vm.CurrentLetterDay;
                lunch = vm.CurrentLunch;

                if (day.ToLower().StartsWith("no"))
                {
                    this.Day = "";
                    this.DayNoSchool = day;
                }
                else
                {
                    this.Day = day;
                }

                this.Lunch = lunch;
            }

            CreateTiles();

            if (System.Diagnostics.Debugger.IsAttached)
                ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(30));

            NotifyComplete();
        }

        private void CreateTiles()
        {
            ShellTile st = ShellTile.ActiveTiles.First();
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                WriteableBitmap imageFront = new WriteableBitmap(173, 173);
                WriteableBitmap imageBack = new WriteableBitmap(173, 173);

                using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    {
                        HomeTile front = new HomeTile();


                        front.DataContext = this;

                        front.UpdateLayout();
                        front.Measure(new Size(173, 173));
                        front.Arrange(new Rect(0, 0, 173, 173));
                        front.UpdateLayout();

                        imageFront.Render(front, null);
                        imageFront.Invalidate();

                        string fileNameFront = "/Shared/ShellContent/TileFront.jpg";
                        using (Stream fileStream = storage.CreateFile(fileNameFront))
                        {
                            imageFront.SaveJpeg(fileStream, 173, 173, 0, 100);
                        }
                    }

                    {
                        HomeTileBack back = new HomeTileBack();

                        back.DataContext = this;

                        back.UpdateLayout();
                        back.Measure(new Size(173, 173));
                        back.Arrange(new Rect(0, 0, 173, 173));
                        back.UpdateLayout();

                        imageBack.Render(back, null);
                        imageBack.Invalidate();

                        string fileNameBack = "/Shared/ShellContent/TileBack.jpg";
                        using (Stream fileStream = storage.CreateFile(fileNameBack))
                        {
                            imageBack.SaveJpeg(fileStream, 173, 173, 0, 100);

                        }
                    }
                }

                if (st != null)
                {
                    StandardTileData std = new StandardTileData()
                    {
                        BackgroundImage = new Uri("isostore:/Shared/ShellContent/TileFront.jpg", UriKind.Absolute),
                        BackBackgroundImage = new Uri("isostore:/Shared/ShellContent/TileBack.jpg", UriKind.Absolute),
                        Title = "",
                        BackTitle = ""
                    };

                    st.Update(std);
                }
            });
        }
    }
}
